<template>
  <el-drawer
    direction="rtl"
    v-model:visible="isShowDialog"
    @close="handleBtnClick({ type: 'close' })" v-model="isShowDialog" :size="px2vw('842px')">
    <template #header>
      <div class=" font-bold pl-[12px]">采购链接</div>
    </template>

    <div class="pl-[12px]">

      <div>
        <el-form :model="form" :rules="rules" label-width="85px">
          <el-row :gutter="24">
            <el-col :span="12"
                    v-for="(item,index) in config"
                    :key="index"
            >
              <el-form-item :prop="item.code" :label="item.name" label-width="85px">
                <el-input v-model="form[item.code]"
                          v-if="!item.type"
                />

                <el-select v-model="form[item.code]" v-if="item.type == 'select'">
                  <el-option v-for="(it,idx) in item.list" :key="idx"
                             :label="it[item.label]"
                             :value="it[item.value]"
                  />
                </el-select>
              </el-form-item>

            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="mt-[30px]">
        <el-button type="primary" color="#3721FF" @click="handleBtnClick({ type: 'add' })">
          添加采购SKU
        </el-button>
        <el-button type="primary" color="#3721FF" @click="handleBtnClick({ type: 'equalShare' })">
          平摊到各SKU
        </el-button>
        <el-button style="color:#3721FF" @click="handleBtnClick({ type:'purchaseLink' })">
          查看采购链接
        </el-button>
      </div>

      <div class="mt-[24px]">
        <QueryTable
          :list="dataList"
          :total="total"
          @execute="handleBtnClick"
          :thead="th"
          :btns="tableBtnList"
          v-model="queryParams"
          :show-action="true"
          :show-section="false"
          :show-expand="false"
          pk="id"
        >

          <template #cover="{row}">
            <ImagePreview width="38px" height="38px" :src="row.cover"/>
          </template>

          <template #productName="{row}">
            <div class="text-[#3721FF]">{{ row.productName }}</div>
          </template>

          <template #purchaseAmount="{row}">
            <el-input-number :min="1" v-model="row.purchaseAmount" style="text-align: center;"
                             :controls="false"/>
          </template>

          <template #purchaseNumber="{row}">
            <el-input-number :controls="false" :min="0" v-model="row.purchaseNumber" type="number"
                             style="text-align: center;"/>
          </template>
        </QueryTable>

      </div>
    </div>


    <ComfirmPops ref="ConfirmPropsRef" :type="'radio'" @confirm="getConfirmValue"
                 title="平摊到各SKU"
                 :show-icon="false" width="537">
      <template #content>
        <EqualShare ref="EqualShareRef"/>
      </template>
    </ComfirmPops>


    <!--    -->

    <ComfirmPops ref="ConfirmPropsRef1" :type="'radio'" @confirm="getConfirmValue1" title="选择sku"
                 :show-icon="false" width="1000">
      <template #content>
        <InfoSku ref="InfoSkuRef" :goodsIds="goodsIds"/>
      </template>
    </ComfirmPops>


    <ComfirmPops ref="ConfirmPropsRef2" :type="'radio'" @confirm="getConfirmValue"
                 title="查看采购链接"
                 :show-icon="false" width="1000">
      <template #content>
        <PurchaseLinkModal :productList="productList" :goodsIds="goodsIds" ref="PurchaseLinkRef"/>
      </template>
    </ComfirmPops>


    <template #footer>
      <div class="dialog-footer flex justify-between pl-[12px]">
        <div class="flex" v-style="`gap:10px`">
          <div> 总共采购：1个sku</div>
          <div> 商品：1个件</div>
          <div> 应付金额：<span class="text-[#3721FF]">￥{{ computeTotal }}</span></div>
        </div>
        <div>
          <el-button @click="handleBtnClick({ type: 'close' })">取 消</el-button>
          <el-button type="primary" @click="handleBtnClick({ type: 'confirm' })">保 存</el-button>
        </div>

      </div>
    </template>


  </el-drawer>
</template>
<script setup lang="ts">
import {listToMap, px2vw} from "@/utils";
import QueryTable from "@/components/TableData/index.vue"
import Icon from "@/components/Icon/src/Icon.vue";
import ImagePreview from "@/components/ImagePreview/index.vue"
import EqualShare from "./EqualShare.vue"
import {confirmPromote} from "@/utils";
import {PurchaseStoreVO, PurchaseStoreApi} from "@/api/purchase/warehouse";
import InfoSku from "./InfoSku.vue"
import PurchaseLinkModal from "./PurchaseLinkModal.vue"


import {PurchaseAdviceVO} from "@/api/erp/purchase/advice";


const props = defineProps({
  modelValue: {
    type: Boolean,
    required: false,
    default: () => false
  },
  info: {
    type: Array,
    required: false,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'confirm']);


const tableBtnList = ref([
  {
    color: '#FF4E00',
    code: 'delItem',
    name: '删除'
  }
])

const goodsIds = ref("")

const ConfirmPropsRef = ref(null);
const EqualShareRef = ref(null);


const ConfirmPropsRef1 = ref(null)
const InfoSkuRef = ref(null)

const ConfirmPropsRef2 = ref(null)
const PurchaseLinkRef = ref(null)

const form = ref({})

const productList = computed(() => {

  let arr = [];
  console.log(dataList.value)
  dataList.value.forEach(item => {
    let it = arr.find(at => {
      return at.productId == item.productId
    })

    console.log(it, "iiiiiiiiiiiiiiii")
    if (!it) {
      arr.push(item)
    }
  })

  return arr;

})


const rules = computed(() => {
  let map = listToMap(config.value, 'code');
  for (let i in map) {
    if (map[i].required) {
      map[i] = [{
        required: true,
        message: `请${map[i].type == 'select' ? '选择' : '输入'}${map[i].name}`,
        trigger: `${map[i].type == 'select' ? 'change' : 'blur'}`
      }]
    }

  }
  return map
})


const isShowDialog = ref(false);

const queryParams = ref({
  pageNo: 1, pageSize: 10
})


const dataList = ref<PurchaseAdviceVO[]>([])
const total = ref(0)
const th = ref([
  {
    name: '图片',
    code: 'cover',
    type: 'numberRanger',
    search: true
  },
  {
    name: 'sku',
    code: 'sku',
    type: 'numberRanger',
    search: true
  },
  {
    name: '商品名称',
    code: 'productName',
    type: 'numberRanger',
    search: true
  },
  {
    name: '商品ID',
    code: 'productId',
    type: 'numberRanger',
    search: true
  },
  {
    name: '属性',
    code: 'property',
    type: 'numberRanger',
    search: true
  },
  {
    name: '采购单价',
    code: 'purchaseAmount',
    type: 'numberRanger',
    search: true
  },
  {
    name: '采购数量',
    code: 'purchaseNumber',
    type: 'numberRanger',
    search: true
  }
])


const config = ref([
  {
    name: "入库仓库",
    type: "select",
    code: "storeId",
    label: "storeName",
    value: "id",
    list: [],
    required: true
  },
  {
    name: "供应商名称",
    code: "supplier",
    required: false
  },
  {
    name: "采购渠道",
    code: "purchasingChannels",
    type: "select",
    label: "name",
    value: "code",
    list: [
      {
        name: "1688",
        code: "1688"
      },
      {
        name: "拼多多",
        code: "拼多多"
      },
      {
        name: "淘宝",
        code: "淘宝"
      },
      {
        name: "京东",
        code: "京东"
      },
      {
        name: "其他",
        code: "其他"
      }
    ],
    required: false
  },
  {
    name: "渠道订单号",
    code: "channelOrder",
    required: false
  },
  {
    name: "采购链接",
    code: "link",
    required: false
  },
  {
    name: "备注",
    code: "remark",
    required: false
  }
])

const computeTotal = computed(() => {
  let price = 0;
  dataList.value.forEach(item => {
    price += (parseFloat(item.purchaseAmount) * parseInt(item.purchaseNumber))
  })
  return price.toFixed(2)
})

const handleBtnClick = (e) => {
  let type = e.type;
  try {
    fn[type](e)
  } catch (e) {
    console.log(`${type}不存在`)
  }

}

const fn = {
  purchaseLink() {
    //添加sku
    // goodsIds.value = dataList.value.map(item => {
    //   return item.productId
    // }).join(",");
    ConfirmPropsRef2.value && ConfirmPropsRef2.value.show();
    // PurchaseLinkRef.value && PurchaseLinkRef.value.queryPurchaseLink( goodsIds.value);
  },
  delItem(e) {
    dataList.value.splice(e.data.index, 1)
    console.log(e)
  },

  add() {
    //添加sku
    goodsIds.value = props.info.map(item => {
      return item.productId
    }).join(",");
    ConfirmPropsRef1.value && ConfirmPropsRef1.value.show();
  },

  close() {
    emit('update:modelValue', false)
  },
  confirm() {
    fn.close();
    console.log(dataList.value, "dataList.value")
    emit('confirm', {
      type: 'purchaseConfirm', data: {
        dataList: dataList.value.map(item => {
          return {
            ...item,
            productName: item.productName,
            productId: item.productId
          }
        }),
        info: props.info,
        form: form.value
      }
    })
  },
  equalShare() {
    ConfirmPropsRef.value.show();
  }
}

const getConfirmValue = async () => {
  let callback = await EqualShareRef.value.confirm();
  let money = callback.money;
  let num = 0;
  dataList.value.forEach(item => {
    num += parseInt(item.purchaseNumber || 0)
  })
  dataList.value.forEach(item => {
    item.purchaseAmount = (parseFloat(money) / num).toFixed(2)
  })
  ConfirmPropsRef.value.hide();
}


/**
 * 选择sku
 * */
const getConfirmValue1 = () => {
  InfoSkuRef.value && InfoSkuRef.value.confirm((productList) => {
    //查看有没有添加该sku
    console.log(productList, "====")
    let list = productList.filter(item => {

      let isIn = dataList.value.find(at => {
        return at.sku == item.sku
      })
      return !isIn
    })

    dataList.value = dataList.value.concat(list.map(item => {
      return {
        sku: item.sku,
        cover: item.picture,
        productName: item.title,
        productId: item.productId,
        property: item.name + '-' + item.nameType,
        purchaseAmount: 0,
        purchaseNumber: 1
      }
    }));

    //关闭弹窗
    ConfirmPropsRef1.value.hide();

  });
}

const initPromise = () => {
  Promise.all([PurchaseStoreApi.getPurchaseStorePage()]).then(res => {
    let list = res[0].list;
    let item = config.value.find(at => {
      return at.code == "storeId"
    })

    item.list = list || []
  })
}

watch(() => props.modelValue, () => {
  isShowDialog.value = props.modelValue;
  if (isShowDialog.value) {
    console.log(props.info, "=====")
    dataList.value = (props.info || []).map(item => {
      return {
        ...item,
        purchaseNumber: item.productSuggestions
      }
    })
    form.value = {}
  }
})

onMounted(() => {
  initPromise()
})

</script>
<style lang="scss" scoped>
:deep(.el-input-number ) {
  width: 100%;
}
</style>
